﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;

namespace Mindfor.Web.Data
{
	/// <summary>
	/// Class for mail queue item data object.
	/// </summary>
	public class MailQueue : IdEntity
	{
		/// <summary>
		/// Gets or sets e-mail address that mail must be send to.
		/// </summary>
		public virtual string ToEmail { get; set; }

		/// <summary>
		/// Gets or sets addressee name.
		/// </summary>
		public virtual string ToName { get; set; }

		/// <summary>
		/// Gets or sets subject.
		/// </summary>
		public virtual string Subject { get; set; }

		/// <summary>
		/// Gets or sets mail body.
		/// </summary>
		public virtual string Body { get; set; }

		/// <summary>
		/// Gets or sets if mail body is in html format or plain text.
		/// </summary>
		public virtual bool IsBodyHtml { get; set; }

		/// <summary>
		/// Gets or sets item create date.
		/// </summary>
		public virtual DateTime CreateDate { get; set; }

		/// <summary>
		/// Gets or sets item send date.
		/// </summary>
		public virtual DateTime? SendDate { get; set; }

		/// <summary>
		/// Converts MailQueue to MailMessage.
		/// </summary>
		/// <returns>MailMessage.</returns>
		public virtual MailMessage ToMailMessage()
		{
			MailMessage m = new MailMessage();
			m.To.Add(new MailAddress(ToEmail, ToName));
			m.Subject = Subject;
			m.Body = Body;
			m.IsBodyHtml = IsBodyHtml;
			return m;
		}

		/// <summary>
		/// Creates new mail queue items from mail message.
		/// Item is created foreach addressee.
		/// </summary>
		/// <param name="message">Mail message to create item from.</param>
		/// <returns>Created queue items.</returns>
		public static IEnumerable<MailQueue> CreateQueueItems(MailMessage message)
		{
			foreach (MailAddress to in message.To)
			{
				// create mail item for each addressee.
				MailQueue item = new MailQueue();
				item.ToEmail = to.Address;
				if (!String.IsNullOrEmpty(to.DisplayName))
					item.ToName = to.DisplayName;
				item.Subject = message.Subject;
				item.Body = message.Body;
				item.IsBodyHtml = message.IsBodyHtml;
				yield return item;
			}
		}
	}
}
